install.packages("tidycensus")19-apis
TidyCensus
Install tidycensus
library(tidycensus)
library(tidyverse)Example call:
acs_mn_2020 <- tidycensus::get_acs(
year = 2020,
state = "MN",
geography = "county",
variables = c("B01003_001", "B19013_001"),
output = "wide",
geometry = TRUE
)Storing your API key
- Create a new text file in the same folder as your .rmd
- Copy and paste your census key into the empty file
- Save the file as
census_api_key.txt
my_key <- readLines("census_api_key.txt")and tell tidycensus what your API key is with:
census_api_key(my_key)Do not commit and push census_api_key.txt to github
httr2
Install if not already installed:
install.packages("httr2")library(httr2)Example call
hmong_state_request <- request("https://api.census.gov/data") %>%
req_url_path_append("2019") %>%
req_url_path_append("acs") %>%
req_url_path_append("acs1") %>%
req_url_query(get = c("NAME", "B02015_009E", "B02015_009M"), `for` = I("state:*"), key = census_api_key, .multi = "comma")hmong_state_response <- req_perform(hmong_state_request)hmong_state_tbl <- hmong_state_response %>%
resp_body_json(simplifyVector = TRUE) %>%
janitor::row_to_names(1) %>%
as_tibble()
hmong_state_tblYour Turn
- Edit the
httrcode to access a new variable of your choice - Make a
httrrequest to access the 1-year ACS data from 2018, 2019, 2021, and 2022. Make sure to save your results from each call! - Combine all years into a single dataset
- Make a time series plot with your chosen variable on the
y-axis, year on thex-axis, colored bystate.- You may want to first filter to only a few states
- You will need to do some cleaning of the data